﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fileencoding=utf-8
# vim:tabstop=4
#
# Copyright (c) 2010 by d.ream.at http://j.mp/bFaTyY
# 
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# 修改自：http://d.ream.at/sync-twitter-timeline-to-renren-status-via-google-app-engine/
#
#    http://www.gnu.org/licenses/fdl.html
#
#    Permission is granted to copy, distribute and/or modify this document
#    under the terms of the GNU Free Documentation License, Version 1.3
#    or any later version published by the Free Software Foundation;
#    with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
#    A copy of the license is included in the section entitled "GNU
#    Free Documentation License".

import Cookie
import urllib
import re
from django.utils import simplejson
from google.appengine.api import urlfetch
#from google.appengine.ext import db
#from google.appengine.ext import webapp
#from google.appengine.ext.webapp.util import run_wsgi_app
 
renren_usr = ''
renren_passwd = ''

cookie_buf = Cookie.SimpleCookie();

def make_cookie_header(cookie):
	ret = ''
	for v in cookie.values():
		ret += '%s=%s;' % (v.key, v.value)
	return ret

def login2renren(renren_usr = renren_usr, renren_passwd = renren_passwd):
	verify_url = 'http://passport.renren.com/PLogin.do'
	verify_data= urllib.urlencode({
		'email':  renren_usr,
		'password': renren_passwd,
		'origURL': 'http://home.renren.com/Home.do',
		'domain': 'renren.com',
		'formName': '',
		'method': '',
		'isplogin': 'true',
		'submit': '登录'
	})
	result = urlfetch.fetch(
		url=verify_url,
		headers={
			'Cookie':make_cookie_header(cookie_buf),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
		},
		method=urlfetch.POST,
		payload=verify_data,
		follow_redirects = False,
	)
	return result
 
def do_redirect(url, cookie):
	result = urlfetch.fetch(
		url=url,
		headers={
			'Cookie':make_cookie_header(cookie),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
		},
		method=urlfetch.GET,
		follow_redirects = False,
	)
	return result

def send_status(status, cookie):
	status_url = 'http://status.renren.com/'
	result = urlfetch.fetch(
		url=status_url,
		headers={
			'Cookie':make_cookie_header(cookie),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
		},
		method=urlfetch.GET,
	)
	cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))
	ticket = re.search('<input type="hidden" value="(-?\d+)" class="submit" id="publisher_form_ticket"/>', result.content)
	status_url = 'http://status.renren.com/doing/update.do?'
	status_data = urllib.urlencode({
		'c': status,
		'raw': status,
		'statusPage': 1,
		'publisher_form_ticket': ticket.group(1),
	})
	result = urlfetch.fetch(
		url=status_url,
		headers={
			'Cookie':make_cookie_header(cookie),
			'Content-Type': 'application/x-www-form-urlencoded',
			'user-agent':'Mozilla/5.0 (Linux; U; Linux i686; en-US) Gecko/20100115 Firefox/3.6',
			'Referer': 'http://status.renren.com/'
		},
		method=urlfetch.POST,
		payload=status_data,
	)
	return True

def rr_sync(properties, timeline):
	global cookie_buf
	renren_usr = properties["username"]
	renren_passwd= properties["password"]
	
	#logging.info("usr = " + renren_usr+ "; pwd = " +renren_passwd )
	if len(timeline) == 0:
		return '<status/>no tweets to sync.'

	result = login2renren(renren_usr, renren_passwd )
	cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''));
	callback_url = result.headers.get('location','xx');
	result = do_redirect(callback_url, cookie_buf)
	cookie_buf = Cookie.SimpleCookie(result.headers.get('set-cookie', ''))

	#print  'before_send_status'
	result = send_status(timeline, cookie_buf)
	return 'ok'

